import Vue from 'vue'
import VueRouter from 'vue-router'

import courseRoutes from './course';
import userRoutes from './user';
import eeRoutes from './ee';
import constants from '../utils/constants';

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: {
            path: '/home',
        }
    },
    {
        path: '/home',
        component: () => import('@/views/Home'),
        redirect: {
            name: 'home'
        },
        children: [
            {
                name: 'home',
                path: 'index'
            },
            {
                path: 'course/list',
                name: 'course-list',
                component: () => import('@/views/course/CourseListView')
            },
            {
                path: 'course/detail/:courseId',
                name: 'course-detail',
                component: () => import('@/views/course/CourseDetailView')
            },
            {
                path: 'course',
                redirect: {
                    name: 'course-list'
                }
            },
            {
                name: 'home-discussion',
                path: 'discussion',
                component: () => import('@/views/discussion/DiscussionListView')
            },
            {
                path: '*',
                redirect: {
                    name: 'home'
                }
            }
        ]
    },
    ...courseRoutes,
    ...userRoutes,
    ...eeRoutes
]

const router = new VueRouter({
    mode: 'history',
    routes
})

router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) {
        let token = window.localStorage.getItem(constants.ACCESS_TOKEN);
        if (token) {
            next()
        } else {
            next({
                name: 'login',
                query: {
                    to: to.fullPath
                }
            });
        }
    } else {
        next();
    }
})

export default router
